import { Body, Controller, Post, Headers } from '@nestjs/common';
import { getResponse, ERROR_CODE, ERROR_MESSAGE, SUCCESS_CODE } from 'src/common/const/const';
import { GoodsNotFoundError, PayOrderFoundError } from 'src/common/utils/error';
import { PayNotificationDto } from './dto/payNotification';
import { PayNotifyService } from './payNotify.service';
import { serviceInfoLog,serviceErrorLog } from "src/common/out/logger/access.logger";

@Controller('payNotify')
export class PayNotifyController {
    constructor(
        private readonly payNotifyService: PayNotifyService,
    ) { }

    // TODO 自定义 httpCode 触发重试机制
    @Post('/notification')
    async payNotification(@Body() payNotificationDto: PayNotificationDto, @Headers() headers: any) {
        try {
            const result = await this.payNotifyService.handlePayNotification(payNotificationDto)
            if (result.success) {
                return getResponse(SUCCESS_CODE.SUCCESS, result.message, {})
            } else {
                return getResponse(ERROR_CODE.INTERNAL_FAIL, result.message, {})
            }
        } catch (error) {
            serviceErrorLog(`payNotification error: ${error}`)
            if (error instanceof PayOrderFoundError) {
                return getResponse(ERROR_CODE.PAY_ORDER_NOT_FOUND, ERROR_MESSAGE[ERROR_CODE.PAY_ORDER_NOT_FOUND], {})
            }
            if (error instanceof GoodsNotFoundError) {
                return getResponse(ERROR_CODE.GOODS_NOT_FOUND, ERROR_MESSAGE[ERROR_CODE.GOODS_NOT_FOUND], {});
            }
            return getResponse(ERROR_CODE.INTERNAL_FAIL, ERROR_MESSAGE[ERROR_CODE.INTERNAL_FAIL], {})
        }
    }
}
